#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

const unsigned int size = 1024;
const int SOCK_ERR = 1;

//程序,ip,port
int main(int argc, char* argv[])
{
    if(argc != 3) exit(-1);
    
    const std::string serverip = argv[1];
    const uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_aton(serverip.c_str(), &server.sin_addr);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0) exit(SOCK_ERR);


    std::string message;
    char buffer[size];
    while(true)
    {
        std::getline(std::cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (const struct sockaddr*)&server, sizeof(server));
        
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&temp, &len);
        buffer[n] = 0;
        std::cout << "server say:" << buffer << std::endl;
    }
    close(sockfd);
    return 0;
}
